﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using HashFoo.Core;
using HashFoo.Rest.Common;
using HashFooRest.App.ServiceDomain.RawData;

namespace HashFooRest.App.Client
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void Echo_Click(object sender, RoutedEventArgs e)
        {
            RunEchoQuery();
            RunEchoCommand();
        }

        void RunEchoCommand()
        {
            var client = CreateClient();

            client.ExecuteCommand(new EchoCommand { EchoResult = "new echo"});
        }

        void RunEchoQuery()
        {
            var client = CreateClient();

            client.Query(
                new ServiceDomain.RawData.EchoQuery { Message = EchoText.Text },
                result => Result.Text = result,
                error => MessageBox.Show(error.ErrorException.ToString()));
        }

        ClientContext CreateClient()
        {
            var baseUri = Application.Current.Host.Source;
            if (baseUri == null) throw new InvalidOperationException();

            var baseUriAsString = baseUri.ToString();
            baseUriAsString = baseUriAsString.Substring(0, baseUriAsString.IndexOf("ClientBin", StringComparison.Ordinal));

            var webClient = new WebRequestClient(baseUriAsString);
            var resourceUris = new ResourceUriCollectionBuilder().AddFromAssemblyOf<ServiceDomain.RawData.EchoQuery>().Build();
            var serializer = new FuncResourceSerializer
            {
                AcceptMimeTypes = new[] { "application/json" },
                ContentMimeType = "application/json",
                Reader = (data, type) => Newtonsoft.Json.JsonConvert.DeserializeObject(data, type),
                Writer = obj => Newtonsoft.Json.JsonConvert.SerializeObject(obj)
            };

            var client = new ClientContext(
                webClient, serializer, resourceUris,
                new FuncDispatcher
                {
                    AsynInvoker = worker => Dispatcher.BeginInvoke(worker),
                    RequiresInvokeChecker = () => (Dispatcher.CheckAccess() == false)
                },
                credentialsProvider:new FakeCredentialsProvider());
            return client;
        }

        private void Authenticate_Click(object sender, RoutedEventArgs e)
        {
            var client = CreateClient();

            client.ExecuteCommand(new FormsAuthCommand { Password = "pass", UserName = "username" });
        }
    }
}
